package com.friend.joey.applicationfriend;

import android.content.Context;
import android.content.Intent;

import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.Trace;
import com.baidu.trace.api.fence.CreateFenceRequest;
import com.baidu.trace.api.fence.CreateFenceResponse;
import com.baidu.trace.api.fence.DeleteFenceRequest;
import com.baidu.trace.api.fence.DeleteFenceResponse;
import com.baidu.trace.api.fence.FenceListRequest;
import com.baidu.trace.api.fence.FenceListResponse;
import com.baidu.trace.api.fence.HistoryAlarmResponse;
import com.baidu.trace.api.fence.MonitoredStatusByLocationResponse;
import com.baidu.trace.api.fence.MonitoredStatusRequest;
import com.baidu.trace.api.fence.MonitoredStatusResponse;
import com.baidu.trace.api.fence.OnFenceListener;
import com.baidu.trace.api.fence.UpdateFenceRequest;
import com.baidu.trace.api.fence.UpdateFenceResponse;
import com.baidu.trace.api.track.HistoryTrackRequest;
import com.baidu.trace.api.track.HistoryTrackResponse;
import com.baidu.trace.api.track.OnTrackListener;
import com.baidu.trace.api.track.SupplementMode;
import com.baidu.trace.api.track.TrackPoint;
import com.baidu.trace.model.CoordType;
import com.baidu.trace.model.OnTraceListener;
import com.baidu.trace.model.ProcessOption;
import com.baidu.trace.model.PushMessage;
import com.baidu.trace.model.TransportMode;
import com.friend.joey.applicationfriend.Classes.MyPoint;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static android.R.id.message;

/**
 * Created by Joey on 2017/5/26.
 */

public class TraceRecord {
    private int total;
    private long serviceId;
    private String entityName;
    private boolean isServerOn=false;
    private Trace mTrace;
    private LBSTraceClient mTraceClient;
    private OnTraceListener mTraceListener;
    private OnTrackListener mTrackListener;
    private OnFenceListener mFenceListener;
    private HistoryTrackRequest historyTrackRequest;
    private List<TrackPoint> tracksList;
    public List<MyPoint> myPoint= new ArrayList<>();
    private onTraceListener traceListener;
    private onTrackListener trackListener;
    private onFenceListener fenceListener;
    public interface onTraceListener{
        void onMBindServiceCallback(int i, String s);
        void onMStartTraceCallback(int status, String message);
        void onMStopTraceCallback(int status, String message);
        void onMStartGatherCallback(int status, String message);
        void onMStopGatherCallback(int status, String message);
        void onMPushCallback(byte messageNo, PushMessage message);
    }
    public interface onTrackListener{
        void onNHistoryTrackCallback(HistoryTrackResponse response);
    }
    public interface onFenceListener{
        // 创建围栏回调
        void onCreateFenceCallback(CreateFenceResponse response);
        // 更新围栏回调
        void onUpdateFenceCallback(UpdateFenceResponse response);
        // 删除围栏回调
        void onDeleteFenceCallback(DeleteFenceResponse response) ;
        // 围栏列表回调
        void onFenceListCallback(FenceListResponse response);
        // 监控状态回调
        void onMonitoredStatusCallback(MonitoredStatusResponse response);
        // 指定位置监控状态回调
        void onMonitoredStatusByLocationCallback(MonitoredStatusByLocationResponse response);
        // 历史报警回调
        void onHistoryAlarmCallback(HistoryAlarmResponse response);
    }
    public void setOnTraceListener(onTraceListener listener){
        this.traceListener=listener;
    }
    public void setOnTrackListener(onTrackListener listener){
        this.trackListener=listener;
    }
    public void setOnFenceListener(onFenceListener listener){
        this.fenceListener=listener;
    }

    public TraceRecord(String entity,Context context){
        // 轨迹服务ID
        serviceId=140820;
        // 设备标识
        entityName =entity;
        boolean isNeedObjectStorage = false;// 是否需要对象存储服务，默认为：false，
        // 初始化轨迹服务
        mTrace = new Trace(serviceId, entityName, isNeedObjectStorage);
        initTraceService(context);
    }
    public void startTrace(){
        mTraceClient.setInterval(5,5);
        mTraceClient.startTrace(mTrace, mTraceListener);
    }
    public void startGather(){
        if(isServerOn) {
            //mTraceClient.startGather(mTraceListener);
        }
        mTraceClient.startGather(mTraceListener);
    }
    public void stopGather(){
        if(isServerOn) {
            //mTraceClient.stopGather(mTraceListener);
        }
        mTraceClient.stopGather(mTraceListener);
    }
    public void stopTrace(){
        if(isServerOn) {
            //mTraceClient.stopTrace(mTrace, mTraceListener);
            //isServerOn=false;
        }
        mTraceClient.stopTrace(mTrace, mTraceListener);

    }
    private void initTraceService(Context context){
        // 初始化轨迹服务客户端
        mTraceClient = new LBSTraceClient(context);
        // 定位周期(单位:秒)
        int gatherInterval = 5;//5
        // 打包回传周期(单位:秒)
        int packInterval = 5;//10
        // 设置定位和打包周期
        mTraceClient.setInterval(gatherInterval, packInterval);
        // 初始化轨迹服务监听器
        mTraceListener = new OnTraceListener() {
            @Override
            public void onBindServiceCallback(int i, String s) {
                if(traceListener!=null) {
                    traceListener.onMBindServiceCallback(i, s);
                }
            }
            // 开启服务回调
            @Override
            public void onStartTraceCallback(int status, String message) {
                //Toast.makeText(TestSpeak.this,"开启"+Integer.toString(status)+message.toString(), Toast.LENGTH_SHORT).show();
                if(status==0){
                    isServerOn=true;
                }
                if(traceListener!=null) {
                    traceListener.onMStartTraceCallback(status, message);
                }
            }
            // 停止服务回调
            @Override
            public void onStopTraceCallback(int status, String message) {
                if(status==0){
                    isServerOn=false;
                }
                if(traceListener!=null) {
                    traceListener.onMStopTraceCallback(status, message);
                }
            }
            // 开启采集回调
            @Override
            public void onStartGatherCallback(int status, String message) {
                if(traceListener!=null) {
                    traceListener.onMStartGatherCallback(status, message);
                }
            }
            // 停止采集回调
            @Override
            public void onStopGatherCallback(int status, String message) {
                if(traceListener!=null) {
                    traceListener.onMStopGatherCallback(status, message);
                }
            }
            // 推送回调
            @Override
            public void onPushCallback(byte messageNo, PushMessage message) {
                //Toast.makeText(TestSpeak.this, "推送", Toast.LENGTH_SHORT).show();
                //Toast.makeText(TestSpeak.this, message.toString(), Toast.LENGTH_SHORT).show();
                if(traceListener!=null) {
                    traceListener.onMPushCallback(messageNo, message);
                }
            }
        };
    }
    private void initTrackInformation(){
        // 请求标识
        int tag = 1;
        // 创建历史轨迹请求实例
        historyTrackRequest = new HistoryTrackRequest(tag, serviceId, entityName);
        //设置轨迹查询起止时间
        // 开始时间(单位：秒)
        long startTime = System.currentTimeMillis() / 1000 - 12 * 60 * 60;
        // 结束时间(单位：秒)
        long endTime = System.currentTimeMillis() / 1000;
        // 设置开始时间
        historyTrackRequest.setStartTime(startTime);
        // 设置结束时间
        historyTrackRequest.setEndTime(endTime);
        // 设置需要纠偏
        historyTrackRequest.setProcessed(true);
        // 创建纠偏选项实例
        ProcessOption processOption = new ProcessOption();
        // 设置需要去噪
        processOption.setNeedDenoise(true);
        // 设置需要抽稀
        processOption.setNeedVacuate(true);
        // 设置需要绑路
        //processOption.setNeedMapMatch(true);
        // 设置精度过滤值(定位精度大于100米的过滤掉)
        processOption.setRadiusThreshold(100);
        // 设置交通方式为驾车
        processOption.setTransportMode(TransportMode.walking);
        // 设置纠偏选项
        historyTrackRequest.setProcessOption(processOption);
        // 设置里程填充方式为驾车
        historyTrackRequest.setSupplementMode(SupplementMode.walking);
        // 初始化轨迹监听器
        mTrackListener = new OnTrackListener() {
            // 历史轨迹回调
            @Override
            public void onHistoryTrackCallback(HistoryTrackResponse response) {
                tracksList=response.getTrackPoints();
                total=response.getTotal();
                for(int i=0;i<total;i++){
                    myPoint.add(new MyPoint(tracksList.get(i)));
                }
                trackListener.onNHistoryTrackCallback(response);
            }
        };
    }
    private void initTrackInformation(long time1,long time2){
        // 请求标识
        int tag = 1;
        // 创建历史轨迹请求实例
        historyTrackRequest = new HistoryTrackRequest(tag, serviceId, entityName);
        //设置轨迹查询起止时间
        // 开始时间(单位：秒)
        long startTime = time1 / 1000 - 12 * 60 * 60;
        // 结束时间(单位：秒)
        long endTime = time2 / 1000;
        // 设置开始时间
        historyTrackRequest.setStartTime(startTime);
        // 设置结束时间
        historyTrackRequest.setEndTime(endTime);
        // 设置需要纠偏
        historyTrackRequest.setProcessed(true);
        // 创建纠偏选项实例
        ProcessOption processOption = new ProcessOption();
        // 设置需要去噪
        processOption.setNeedDenoise(true);
        // 设置需要抽稀
        processOption.setNeedVacuate(true);
        // 设置需要绑路
        //processOption.setNeedMapMatch(true);
        // 设置精度过滤值(定位精度大于100米的过滤掉)
        processOption.setRadiusThreshold(100);
        // 设置交通方式为驾车
        processOption.setTransportMode(TransportMode.walking);
        // 设置纠偏选项
        historyTrackRequest.setProcessOption(processOption);
        // 设置里程填充方式为驾车
        historyTrackRequest.setSupplementMode(SupplementMode.walking);
        // 初始化轨迹监听器
        mTrackListener = new OnTrackListener() {
            // 历史轨迹回调
            @Override
            public void onHistoryTrackCallback(HistoryTrackResponse response) {
                tracksList=response.getTrackPoints();
                total=response.getTotal();
                for(int i=0;i<total;i++){
                    myPoint.add(new MyPoint(tracksList.get(i)));
                }
                trackListener.onNHistoryTrackCallback(response);
            }
        };
    }
    private void initFenceListener(){
        // 初始化围栏监听器
        mFenceListener = new OnFenceListener() {
            // 创建围栏回调
            @Override
            public void onCreateFenceCallback(CreateFenceResponse response) {
                fenceListener.onCreateFenceCallback(response);
            }
            // 更新围栏回调
            @Override
            public void onUpdateFenceCallback(UpdateFenceResponse response) {
                fenceListener.onUpdateFenceCallback(response);
            }
            // 删除围栏回调
            @Override
            public void onDeleteFenceCallback(DeleteFenceResponse response) {
                fenceListener.onDeleteFenceCallback(response);
            }
            // 围栏列表回调
            @Override
            public void onFenceListCallback(FenceListResponse response) {
                fenceListener.onFenceListCallback(response);
            }
            // 监控状态回调
            @Override
            public void onMonitoredStatusCallback(MonitoredStatusResponse response) {
                fenceListener.onMonitoredStatusCallback(response);
            }
            // 指定位置监控状态回调
            @Override
            public void onMonitoredStatusByLocationCallback(MonitoredStatusByLocationResponse response) {
                fenceListener.onMonitoredStatusByLocationCallback(response);
            }
            // 历史报警回调
            @Override
            public void onHistoryAlarmCallback(HistoryAlarmResponse response) {
                fenceListener.onHistoryAlarmCallback(response);
            }
        };
    }
    private void initFenceInformation(){
        // 请求标识
        int tag = 2;
        // 围栏名称
        String fenceName = "home";
        // 围栏圆心
        com.baidu.trace.model.LatLng center = new com.baidu.trace.model.LatLng(37.5330929990, 122.08964860478);
        // 围栏半径（单位 : 米）
        double radius = 60;//2000
        // 去噪精度
        int denoise = 50;//200
        // 坐标类型
        CoordType coordType = CoordType.bd09ll;
        // 创建本地圆形围栏请求实例
        CreateFenceRequest localCircleFenceRequest = CreateFenceRequest.buildLocalCircleRequest(tag, serviceId,fenceName, entityName, center, radius, denoise, coordType);
        initFenceListener();
        // 创建本地圆形围栏
        mTraceClient.createFence(localCircleFenceRequest, mFenceListener);
    }
    private void initFenceCheckInformation(){
        int tag=3;
        List<Long> fenceIds=null;
        //创建查询服务端围栏监控状态请求
        MonitoredStatusRequest request=MonitoredStatusRequest.buildLocalRequest(tag,
                serviceId,entityName,fenceIds);
        initFenceListener();
        //查询围栏监控者状态
        mTraceClient.queryMonitoredStatus(request,mFenceListener);

    }
    public void deleteFence(){
        // 请求标识
        int tag = 4;
        List<Long> fenceIds=null;
        DeleteFenceRequest request = DeleteFenceRequest.buildLocalRequest(tag,serviceId,entityName,fenceIds);
        initFenceListener();
        // 创建本地圆形围栏
        mTraceClient.deleteFence(request, mFenceListener);
    }
    public void startCheck(){
        // 查询历史轨迹
        initTrackInformation();
        mTraceClient.queryHistoryTrack(historyTrackRequest, mTrackListener);
    }
    public void startCheck(long time1,long time2){
        initTrackInformation(time1,time2);
        mTraceClient.queryHistoryTrack(historyTrackRequest, mTrackListener);
    }
    public void updateFence(){
        // 请求标识
        int tag = 5;
        // 围栏名称
        long fenceId=105L;
        String fenceName = "home";
        // 围栏圆心
        com.baidu.trace.model.LatLng center = new com.baidu.trace.model.LatLng(37.5330929990, 122.08964860478);
        // 围栏半径（单位 : 米）
        double radius = 60;//2000
        // 去噪精度
        int denoise = 50;//200
        // 坐标类型
        CoordType coordType = CoordType.bd09ll;
        //
//        List<Long> fenceIds=null;
//        fenceIds.add(104L);
        UpdateFenceRequest request = UpdateFenceRequest.buildLocalCircleRequest(tag,serviceId,fenceId,fenceName,entityName,center, radius, denoise, coordType);
        initFenceListener();
        // 创建本地圆形围栏
        mTraceClient.updateFence(request, mFenceListener);
    }
    public void setFence(){
        initFenceInformation();
    }
    public void checkFence(){
        //initFenceCheckInformation();
        int tag=3;
        List<Long> fenceIds=null;
        //创建查询服务端围栏监控状态请求
        FenceListRequest request=FenceListRequest.buildLocalRequest(tag, serviceId,entityName,fenceIds);
        initFenceListener();
        //查询围栏监控者状态
        mTraceClient.queryFenceList(request,mFenceListener);
    }
    public Intent getMyIntent(){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.SHOWTRACE");
        //intent.putExtra("total",total);
        //intent.putExtra("points", (Serializable) myPoint);
        intent.putExtra("total",total);
        intent.putExtra("points", (Serializable) myPoint);
        return intent;
    }
    public String myPointToString(){
        String string=new String("MyPoints:");
        return string;
    }
    public int getTotal(){
        return total;
    }
    public List<TrackPoint> getTracksList(){
        return tracksList;
    }
    public boolean getServeState(){
        return isServerOn;
    }
    public List<MyPoint> getMyPoint(){
        return myPoint;
    }
    public MyPoint getFirstPoint(){
        return myPoint.get(0);
    }
}
